package org.hs.phd.odi.tracking.ui.trackInitialization;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.event.MouseEvent;

import org.hs.phd.common.frameviewer.FrameViewer;
import org.hs.phd.common.frameviewer.ViewerLayer;

public class FixedWindowTrackInitiationLayer implements ViewerLayer {
	
	private final int dx;
	private final int dy;
	private TrackInitializationListener listener;
	private FrameViewer viewer;
	private Polygon polygon;
	private boolean isEnabled;

	public FixedWindowTrackInitiationLayer( TrackInitializationListener listener, int dx, int dy  ){
		this.listener = listener;
		this.isEnabled = true;
		this.dx = dx;
		this.dy = dy;
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		// do nothing
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// do nothing
		
	}

	@Override
	public void mouseExited(MouseEvent e) {
		// do nothing
	}

	@Override
	public void mousePressed(MouseEvent e) {
		Point modelPoint = viewer.getTransformation().viewToModel(e.getX(), e.getY());
		int x = modelPoint.x; 
		int y = modelPoint.y;
		
		polygon = new Polygon();
		polygon.addPoint(x - dx, y - dy);
		polygon.addPoint(x + dx, y - dy);
		polygon.addPoint(x + dx, y + dy);
		polygon.addPoint(x - dx, y + dy);
		viewer.repaint();
	
		listener.trackInitialized(polygon);
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// do nothing
	}

	@Override
	public void mouseDragged(MouseEvent e) {
		// do nothing
	}

	@Override
	public void mouseMoved(MouseEvent e) {
		// do nothing
	}

	@Override
	public void setViewer(FrameViewer viewer) {
		this.viewer = viewer;
	}

	@Override
	public void paint(Graphics g) {
		if(polygon != null){
			Polygon viewShape = viewer.getTransformation().modelToView(polygon);
			
			Graphics2D g2 = (Graphics2D) g;
			g2.setColor(Color.RED);
			g2.drawPolygon(viewShape);
		}
	}

	@Override
	public void setEnabled(boolean isEnabled) {
		polygon = null;
		this.isEnabled = isEnabled;
	}

	@Override
	public boolean isEnabled() {
		return isEnabled;
	}

}
